<template>
	<div class="image-upload-container">
		<el-upload
			:headers="headers"
			:action="baseURL + uploadUrl"
			list-type="picture-card"
			:auto-upload="autoUpload"
			:file-list="fileList"
			:on-success="handleSuccess"
			:on-change="handleChange"
			:on-remove="handleRemove"
			:on-preview="handlePreview"
			:limit="limit"
			:multiple="multiple"
		>
			<el-icon><Plus /></el-icon>
			<template #tip>
				<div class="el-upload__tip" v-if="tip">
					{{ tip }}
				</div>
			</template>
		</el-upload>

		<!-- 图片预览对话框 -->
		<el-dialog v-model="previewVisible" width="50%">
			<img :src="previewUrl" alt="Preview Image" style="width: 100%" />
		</el-dialog>
	</div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { Session } from '/@/utils/storage';
// import { service } from '/@/utils/request';
import { Plus } from '@element-plus/icons-vue';
import { useMessage } from '/@/hooks/message';

const props = defineProps({
	modelValue: {
		type: String,
		default: '',
	},
	uploadUrl: {
		type: String,
		default: '/admin/sys-file/upload',
	},
	limit: {
		type: Number,
		default: 5,
	},
	autoUpload: {
		type: Boolean,
		default: true,
	},
	multiple: {
		type: Boolean,
		default: true,
	},
	tip: {
		type: String,
		default: '支持jpg/png格式',
	},
});

const emit = defineEmits(['update:modelValue', 'change']);

// 定义baseURL
// const baseURL = computed(() => service.defaults.baseURL || '');

// 请求头
const headers = computed(() => {
	return {
		Authorization: 'Bearer ' + Session.getToken(),
		'TENANT-ID': Session.getTenant(),
	};
});

// 文件列表
const fileList = ref([]);

// 预览相关
const previewVisible = ref(false);
const previewUrl = ref('');

// 监听modelValue变化，更新文件列表
watch(
	() => props.modelValue,
	(val) => {
		if (val) {
			try {
				// 将逗号分隔的URL字符串转换为文件列表
				fileList.value = val.split(',').map((url) => ({
					name: url.substring(url.lastIndexOf('/') + 1),
					url: url,
					status: 'success',
				}));
			} catch (error) {
				console.error('Error processing image URLs:', error);
				fileList.value = [];
			}
		} else {
			fileList.value = [];
		}
	},
	{ immediate: true },
);

// 上传成功处理
function handleSuccess(response, file, fileList) {
	console.log('Upload success:', response, file, fileList);
	if (response.code === 0) {
		// 更新modelValue
		updateModelValue(fileList);
		useMessage().success('上传成功');
	} else {
		useMessage().error(response.msg || '上传失败');
	}
}

// 文件状态改变处理
function handleChange(file, fileList) {
	console.log('File change:', file, fileList);
	// 如果是自动上传，则不需要在这里处理
	if (!props.autoUpload && file.status === 'ready') {
		// 这里可以添加手动上传逻辑
		console.log('文件准备上传:', file);
	}
}

// 移除文件处理
function handleRemove(file, fileList) {
	console.log('File removed:', file, fileList);
	// 更新modelValue
	updateModelValue(fileList);
}

// 预览文件
function handlePreview(file) {
	console.log('Preview file:', file);
	previewUrl.value = file.url;
	previewVisible.value = true;
}

// 更新modelValue
function updateModelValue(fileList) {
	try {
		// 从文件列表中提取URL
		const urls = fileList
			.filter((file) => {
				// 处理已上传成功的文件
				if (file.status === 'success') {
					if (
						file.response &&
						file.response.data &&
						file.response.data.ossUrl
					) {
						return true;
					}
					if (file.url) {
						return true;
					}
				}
				return false;
			})
			.map((file) => {
				// 返回文件URL
				if (file.response && file.response.data && file.response.data.ossUrl) {
					return file.response.data.ossUrl;
				}
				return file.url;
			});

		console.log('Updated URLs:', urls);
		// 更新modelValue
		emit('update:modelValue', urls.join(','));
	} catch (error) {
		console.error('Error updating model value:', error);
	}
}
</script>

<style lang="scss" scoped>
.image-upload-container {
	:deep(.el-upload--picture-card) {
		border-radius: 6px;
		border: 1px dashed #d9d9d9;
		transition: all 0.3s;
		width: 120px;
		height: 120px;

		&:hover {
			border-color: #409eff;
			color: #409eff;
		}
	}

	:deep(.el-upload-list--picture-card .el-upload-list__item) {
		border-radius: 6px;
		overflow: hidden;
		width: 120px;
		height: 120px;
	}

	.el-upload__tip {
		color: #909399;
		font-size: 12px;
		margin-top: 5px;
		line-height: 1.4;
	}
}
</style>
